/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.acceptance.util.worker;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import org.easymock.classextension.EasyMock;
import org.ourgrid.acceptance.util.WorkerAcceptanceUtil;
import org.ourgrid.common.interfaces.Worker;
import org.ourgrid.common.interfaces.WorkerClient;
import org.ourgrid.common.interfaces.management.WorkerManagement;
import org.ourgrid.common.interfaces.management.WorkerManagementClient;
import org.ourgrid.matchers.BeginAllocationRunnableMatcher;
import org.ourgrid.matchers.ValidWorkerMatcher;
import org.ourgrid.worker.WorkerComponent;
import org.ourgrid.worker.WorkerConfiguration;
import org.ourgrid.worker.WorkerConstants;

import br.edu.ufcg.lsd.commune.container.ContainerContext;
import br.edu.ufcg.lsd.commune.container.ObjectDeployment;
import br.edu.ufcg.lsd.commune.container.logging.CommuneLogger;
import br.edu.ufcg.lsd.commune.container.servicemanager.FileTransferManager;
import br.edu.ufcg.lsd.commune.identification.ContainerID;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;
import br.edu.ufcg.lsd.commune.identification.ServiceID;
import br.edu.ufcg.lsd.commune.network.xmpp.XMPPProperties;
import br.edu.ufcg.lsd.commune.processor.filetransfer.IncomingTransferHandle;
import br.edu.ufcg.lsd.commune.processor.filetransfer.OutgoingTransferHandle;
import br.edu.ufcg.lsd.commune.processor.filetransfer.TransferHandle;
import br.edu.ufcg.lsd.commune.test.AcceptanceTestUtil;


public class Req_092_Util extends WorkerAcceptanceUtil{
	
	public Req_092_Util(ContainerContext context) {
		super(context);
	}

	public void workForMyGridOnOwnerWorker(WorkerComponent component, WorkerManagementClient wmc) {
		workForMyGrid(component, wmc, null, null, false, true, false, false, false, null, null);
	}

	public Future<?> workForMyGridOnIdleWorker(WorkerComponent component, WorkerManagementClient wmc, 
			String myGridPubKey) {
		return workForMyGrid(component, wmc, null, myGridPubKey, true, false, false, false, false, null, null);
	}
	
	public Future<?> workForMyGridOnAllocatedForMyGridWorker(WorkerComponent component, WorkerManagementClient wmc,
			String myGridPubKey) {
		return workForMyGrid(component, wmc, null, myGridPubKey, false, false, false, true, false, null, null);
	}
	
	public Future<?> workForMyGridOnAllocatedForMyGridWorkerWithFileOnTransfer(WorkerComponent component,
			WorkerManagementClient wmc,	String myGridPubKey, boolean isIncomingTransfer, List<TransferHandle> handles) {
		return workForMyGrid(component, wmc, null, myGridPubKey, false, false, false, true, isIncomingTransfer, null, handles);
	}

	public Future<?> workForMyGridOnAllocatedForMyGridWorkerWithCleaningError(WorkerComponent component,
			WorkerManagementClient wmc, String myGridPubKey, String playpenDirWithError) {
		return workForMyGrid(component, wmc, null, myGridPubKey, false, false, false, true, false, playpenDirWithError, null);
	}
	
	public Future<?> workForMyGridOnAllocatedForMyGridWorkerWithCleaningErrorAndFileOnTransfer(WorkerComponent component, 
			WorkerManagementClient wmc,
			String myGridPubKey, String playpenDirWithError, List<TransferHandle> handles) {
		return workForMyGrid(component, wmc, null, myGridPubKey, false, false, false, true, true, playpenDirWithError, handles);
	}
	
	public Future<?> workForMyGridOnAllocatedForPeerWorker(WorkerComponent component, WorkerManagementClient wmc, 
			String myGridPubKey) {
		return workForMyGrid(component, wmc, null, myGridPubKey, false, false, true, true, false, null, null);
	}
	
	public void workForMyGridBeforeSetPeer(WorkerComponent component) {
		workForMyGrid(component, null);
	}

	public void workForMyGrid(WorkerComponent component, String senderPublicKey) {
		workForMyGrid(component, null, senderPublicKey, null, false, false, false, false, false, null, null);
	}

	private Future<?> workForMyGrid(WorkerComponent component, WorkerManagementClient wmc, String senderPublicKey,
			String myGridPubKey, boolean isWorkerIdle, boolean isWorkerOwner, boolean isWorkerAllocatedForPeer,
			boolean cleans, boolean isIncomingFile, String playpenDirWithError, List<TransferHandle> handles) {
		CommuneLogger oldLogger = component.getLogger();
		CommuneLogger newLogger = EasyMock.createMock(CommuneLogger.class);
		component.setLogger(newLogger);
		
		WorkerClient workerClient = EasyMock.createMock(WorkerClient.class);
		DeploymentID myGridID = new DeploymentID(new ContainerID("username", "server", "module", myGridPubKey), "broker");
		
		AcceptanceTestUtil.publishTestObject(application, myGridID, workerClient, WorkerClient.class);

		WorkerManagement workerManag = getWorkerManagement();
		ObjectDeployment wmOD = getWorkerManagementDeployment();

		FileTransferManager ftm = EasyMock.createMock(FileTransferManager.class);
		component.setFileTransferManager(ftm);
		
		ExecutorService newThreadPool = EasyMock.createMock(ExecutorService.class);
		component.setExecutorThreadPool(newThreadPool);
		
		Future future = null;
		
		if (senderPublicKey != null) {
			newLogger.warn("An unknown peer tried to command this Worker to work for a local consumer. This message was ignored." +
					" Unknown peer public key: [" + senderPublicKey + "].");
		} else {
			senderPublicKey =
					context.getProperty(WorkerConfiguration.PROP_PEER_PUBLIC_KEY);
		
			if (wmc != null) {
				
				if (isWorkerIdle) {
					newLogger.info("Peer commanded this Worker to work for a local consumer." +
							" Local consumer public key: [" +  myGridID + "].");
					newLogger.debug("Status changed from IDLE to ALLOCATED_FOR_BROKER.");
					newLogger.debug("Worker begin allocation action, preparing to start the working.");

					future = EasyMock.createMock(Future.class);
					
					EasyMock.expect(
							newThreadPool.submit(
									BeginAllocationRunnableMatcher.eqMatcher(createBeginAllocationRunnable())))
									.andReturn(future).once();
					
				} else {
					
					if (!isWorkerOwner) {
						newLogger.info("Peer commanded this Worker to work for a local consumer." +
								" Local consumer public key: [" +  myGridID + "].");
						
						if(isWorkerAllocatedForPeer) {
							newLogger.debug("Status changed from ALLOCATED_FOR_PEER to ALLOCATED_FOR_BROKER.");
						}
						if(cleans) {
							newLogger.debug("Cleaning Worker.");
							if (playpenDirWithError != null) {
								newLogger.error("Error while trying to clean the playpen directory [" + playpenDirWithError +"].");	
							}
							if(handles != null) {
								if(isIncomingFile) {
									for (TransferHandle handle : handles) {
										ftm.cancelIncomingTransfer((IncomingTransferHandle) handle);
									}
								} else {
									for (TransferHandle handle : handles) {
										ftm.cancelOutgoingTransfer((OutgoingTransferHandle)handle);
									}
								}
								EasyMock.replay(ftm);
							}
						} 
						
						newLogger.debug("Worker begin allocation action, preparing to start the working.");

					} else {
						newLogger.debug("This Worker was commanded to work for a local consumer," +
						" but it is in the OWNER status. This message was ignored.");
					}
				}

			} else {
				newLogger.debug("The master Peer tried to manage this Worker before setting itself as manager of this Worker." +
				" This message was ignored.");
			}
		}

		EasyMock.replay(newLogger);
		
		DeploymentID peerID = new DeploymentID(new ContainerID("peerUser", "peerServer", "peer", senderPublicKey), "broker");
		
		AcceptanceTestUtil.setExecutionContext(component, wmOD, peerID);
		
		workerManag.workForBroker(myGridID);
		
		EasyMock.verify(newLogger);
		
		if (handles != null) {
			EasyMock.verify(ftm);
		}
		
		if (future != null) {
			EasyMock.reset(future);
		}
		
		component.setLogger(oldLogger);
		
		return future;
	}

	public Worker beginAllocationCompleted(WorkerComponent component, WorkerManagementClient wmc) {
		
		CommuneLogger oldLogger = component.getLogger();
		CommuneLogger newLogger = EasyMock.createMock(CommuneLogger.class);
		component.setLogger(newLogger);
		
		ObjectDeployment wmOD = getWorkerManagementDeployment();
		
		ServiceID workerEntityID = new ServiceID(new ContainerID(
				context.getProperty(XMPPProperties.PROP_USERNAME), 
				context.getProperty(XMPPProperties.PROP_XMPP_SERVERNAME), 
				WorkerConstants.WORKER, wmOD.getDeploymentID().getPublicKey()), WorkerConstants.WORKER);
		
		newLogger.debug("Allocation action was completed.");
		
		EasyMock.reset(wmc);
		wmc.statusChangedAllocatedForBroker(ValidWorkerMatcher.eqMatcher(getServiceManager(), workerEntityID));
		EasyMock.replay(wmc);
		EasyMock.replay(newLogger);
	
		getWorkerExecutionClient().readyForAllocation();
		
		EasyMock.verify(wmc);
		EasyMock.reset(wmc);
		
		EasyMock.verify(newLogger);
		
		component.setLogger(oldLogger);
		
		return getWorker();
	}
}
